global DISPLAY_ID, PLAYER_VERSION, RVPLAYER, CHROME_MAC, CORE_URL, SHOW_URL, TYPE_CHROMIUM, TYPE_INSTALLER, HOME_PATH, INSTALL_PATH, PARAM_RESTART, PARAM_INSTALLER_UPGRADE, PARAM_CHROMIUM_VERSION, PARAM_CHROMIUM_URL, VALUE_NO, VALUE_YES, VALUE_RESTART, VALUE_INSTALLER_UPGRADE, VALUE_CHROMIUM_VERSION, VALUE_CHROMIUM_URL, PREFERENCES_CONTENT, CACHE_PATH, CONFIG_PATH, PREFERENCES_PATH, FIRST_RUN_FILE, PREFERENCES_FILE, TEMP_PATH, CHROME_MAC_PATH, STARTUP_APPLE_SCRIPT, STARTUP_SHELL_SCRIPT, UPGRADE_NEEDED

set DISPLAY_ID to "#DISPLAY_ID#" 
set PLAYER_VERSION to "1.0.0007-test"
-- set PLAYER_VERSION to "1.0.0007"

set RVPLAYER to "rvplayer"
set CHROME_MAC to "chrome-mac"

set CORE_URL to "https://rvacore-test.appspot.com"
-- set CORE_URL to "https://rvaserver2.appspot.com"
set SHOW_URL to "http://viewer-test.appspot.com"
-- set SHOW_URL to "http://rvashow.appspot.com"

set TYPE_CHROMIUM to "chromium"
set TYPE_INSTALLER to "installer"

set HOME_PATH to do shell script "echo $HOME"
set INSTALL_PATH to HOME_PATH & "/" & RVPLAYER

set PARAM_RESTART to "Restart"
set PARAM_INSTALLER_UPGRADE to "InstallerUpgrade"
set PARAM_CHROMIUM_VERSION to "ChromiumVersion"
set PARAM_CHROMIUM_URL to "ChromiumURL"

set VALUE_NO to "0"
set VALUE_YES to "1"

set VALUE_RESTART to VALUE_NO
set VALUE_INSTALLER_UPGRADE to VALUE_NO
set VALUE_CHROMIUM_VERSION to ""
set VALUE_CHROMIUM_URL to ""

set PREFERENCES_CONTENT to "{\\042countryid_at_install\\042:0,\\042default_search_provider\\042:{\\042enabled\\042:false},\\042geolocation\\042:{\\042default_content_setting\\042:1},\\042profile\\042:{\\042content_settings\\042:{\\042pref_version\\042:1},\\042exited_cleanly\\042:true}}"

set CONFIG_PATH to HOME_PATH & "/Library/Application Support/" & RVPLAYER
set PREFERENCES_PATH to CONFIG_PATH & "/Default"
set CACHE_PATH to HOME_PATH & "/Library/Caches/" & RVPLAYER
set FIRST_RUN_FILE to "First Run"
set PREFERENCES_FILE to "Preferences"

set TEMP_PATH to INSTALL_PATH & "/temp"
set CHROME_MAC_PATH to TEMP_PATH & "/" & CHROME_MAC

set STARTUP_APPLE_SCRIPT to INSTALL_PATH & "/rvplayer.applescript"
set STARTUP_SHELL_SCRIPT to INSTALL_PATH & "/rvplayer.command"

set UPGRADE_NEEDED to VALUE_NO

to split(someText, delimiter)
	
	set AppleScript's text item delimiters to delimiter
	set someText to someText's text items
	set AppleScript's text item delimiters to {""}
	return someText
	
end split

on folderExists(posixPath)
	return ((do shell script "if [ -d " & posixPath & " ]; then echo 1; else echo 0; fi") as integer) as boolean
end folderExists

on recordError(msg, num)
	log "Error: " & msg
end recordError

on rvp_get_update()
	
	local curr_date, chromium_ver, update_url, update_content, update_lines, update_line, update_name_value, p_name, p_value
	
	set curr_date to do shell script "echo $(date +%d%m%Y%H%M)"
	set chromium_ver to do shell script "echo `cat " & INSTALL_PATH & "/" & TYPE_CHROMIUM & "_version 2>/dev/null` || echo"
	
	set update_url to CORE_URL & "/player/update?os=mac&id=" & DISPLAY_ID & "&ts=" & curr_date & "&iv=" & PLAYER_VERSION & "&cv=" & chromium_ver
	
	log "Checking for updates..."
	try
		set update_content to do shell script "curl \"" & update_url & "\""
		
		if (update_content is not equal to "") then
			
			set update_lines to split(update_content, return)
			repeat with update_line in update_lines
				
				set update_name_value to split(update_line, "=")
				set p_name to item 1 of update_name_value
				set p_value to item 2 of update_name_value
				
				if (p_name = PARAM_RESTART) then
					set VALUE_RESTART to p_value
				else if (p_name = PARAM_INSTALLER_UPGRADE) then
					set VALUE_INSTALLER_UPGRADE to p_value
				else if (p_name = PARAM_CHROMIUM_VERSION) then
					set VALUE_CHROMIUM_VERSION to p_value
				else if (p_name = PARAM_CHROMIUM_URL) then
					set VALUE_CHROMIUM_URL to p_value
				end if
				
			end repeat
			
		else
			log "Update check failed!"
		end if
		
	on error errStr number errorNumber
		recordError(errStr, errorNumber)
		log "Update check failed!"
	end try
	
end rvp_get_update

on rvp_restart()
	
	if (folderExists(INSTALL_PATH & "/Chromium.app")) then
		tell application "Finder" to get name of application file id "org.chromium.Chromium"
		tell application result
			quit
		end tell
	end if
	
	delay 10
	
	-- clear Chromium cache
	
	do shell script "rm -rf \"" & CACHE_PATH & "\""
	
	tell application "Finder"
		restart
	end tell
	
end rvp_restart

on rvp_download_and_run_installer()
	
	local curr_path, installer_url
	
	set curr_path to (the POSIX path of (path to me))
	set installer_url to CORE_URL & "/player/download?os=mac&displayId=" & DISPLAY_ID
	
	-- downloading installer
	
	log "Downloading installer..."
	do shell script "curl \"" & installer_url & "\" -o \"" & curr_path & "\" --retry 3"
	log "Download complete."
	
	-- exit this version and let new version take over
	
	do shell script "osascript " & curr_path & " &"
	error number -128
	
end rvp_download_and_run_installer

on rvp_install_script()
	
	local curr_path
	
	do shell script "mkdir -p " & INSTALL_PATH
	
	set curr_path to (the POSIX path of (path to me))
	
	if (curr_path is not equal to STARTUP_APPLE_SCRIPT) then
		
		do shell script "cp " & curr_path & " " & STARTUP_APPLE_SCRIPT
		do shell script "echo 'osascript " & STARTUP_APPLE_SCRIPT & "' > " & STARTUP_SHELL_SCRIPT
		do shell script "chmod a+x " & STARTUP_SHELL_SCRIPT
		log "Startup scripts updated"
		
	end if
	
end rvp_install_script

on rvp_download_and_unpack_chromium()
	
	try
		
		do shell script "rm -rf " & TEMP_PATH
		do shell script "mkdir -p " & TEMP_PATH
		
		-- downloading zip
		
		log "Downloading Chromium..."
		do shell script "rm -f " & CHROME_MAC_PATH & ".zip"
		do shell script "cd " & TEMP_PATH & " ; curl \"" & VALUE_CHROMIUM_URL & "\" -o \"" & CHROME_MAC & ".zip\" --retry 3"
		log "Download complete."
		
		-- unzipping
		
		do shell script "rm -rf " & CHROME_MAC_PATH & "*/"
		do shell script "cd " & TEMP_PATH & " ; unzip " & CHROME_MAC & ".zip"
		do shell script "rm -f " & CHROME_MAC_PATH & ".zip"
		
	on error errStr number errorNumber
		recordError(errStr, errorNumber)
		log "Chromium download failed!"
	end try
	
end rvp_download_and_unpack_chromium

on rvp_install_chromium()
	
	if (folderExists(INSTALL_PATH & "/Chromium.app")) then
		tell application "Finder" to get name of application file id "org.chromium.Chromium"
		tell application result
			quit
		end tell
	end if
	
	delay 5
	
	do shell script "cd " & CHROME_MAC_PATH & " ; find * -print | cpio -pvdmu " & INSTALL_PATH & "/"
	do shell script "rm -rf " & CHROME_MAC_PATH & "*/"
	do shell script "echo " & VALUE_CHROMIUM_VERSION & " > " & INSTALL_PATH & "/" & TYPE_CHROMIUM & "_version"
	do shell script "rm -rf " & TEMP_PATH
	
	log "New Chromium version installed."
	
	-- wipe Chromium cache and profile
	do shell script "rm -rf \"" & CACHE_PATH & "\""
	do shell script "rm -rf \"" & CONFIG_PATH & "\""
	
	log "Cache and profile cleared."
	
	
end rvp_install_chromium

on rvp_add_player_to_autostart()
	
	try
		
		tell application "System Events"
			get exists login item "RVPlayer"
			if result is false then
				make new login item at end of login items with properties {path:STARTUP_SHELL_SCRIPT, hidden:true, name:"RVPlayer"}
			end if
		end tell
		
	on error errStr number errorNumber
		recordError(errStr, errorNumber)
		log "Player will not be able to start automatically!"
	end try
	
end rvp_add_player_to_autostart

on rvp_install_to_crontab()
	
	try
		
		-- run every 10 min
		do shell script "echo \"*/10 * * * * " & STARTUP_SHELL_SCRIPT & " > " & STARTUP_SHELL_SCRIPT & ".log 2>&1\" | crontab -"
		
	on error errStr number errorNumber
		recordError(errStr, errorNumber)
		log "Player will not be able to check for updates at regular intervals!"
	end try
	
end rvp_install_to_crontab

on rvp_start_player()
	
	local process_list
	
	tell application "System Events" to get name of every process
	set process_list to result
	if process_list contains "Chromium" then
		log "Rise Player is already running"
	else
		
		if (not folderExists(INSTALL_PATH & "/Chromium.app")) then
			log "Chromium is not installed?"
			return
		end if
		
		do shell script "mkdir -p \"" & CONFIG_PATH & "\""
		do shell script "mkdir -p \"" & PREFERENCES_PATH & "\""
		do shell script "mkdir -p \"" & CACHE_PATH & "\""
		do shell script ":>\"" & CONFIG_PATH & "/" & FIRST_RUN_FILE & "\""
		do shell script "echo '" & PREFERENCES_CONTENT & "' > \"" & PREFERENCES_PATH & "/" & PREFERENCES_FILE & "\""
		
		log "Starting Rise Player..."
		
		try
			
			do shell script INSTALL_PATH & "/Chromium.app/Contents/MacOS/Chromium --no-default-browser-check --noerrdialogs --no-message-box --disable-desktop-notifications --disk-cache-dir=\"" & CACHE_PATH & "\" --user-data-dir=\"" & CONFIG_PATH & "\" " & SHOW_URL & "/Viewer.html?type=display\\&id=" & DISPLAY_ID & " > /dev/null 2>&1 &"
			delay 10
			
			tell application "Finder" to get name of application file id "org.chromium.Chromium"
			tell application result
				activate
				tell application "System Events"
					key down {command}
					key down {shift}
					keystroke "f"
					key up {shift}
					key up {command}
				end tell
			end tell
			
		on error errStr number errorNumber
			recordError(errStr, errorNumber)
			log "Chromium failed to start!"
		end try
		
	end if
	
end rvp_start_player

on rvp_update_system()
	
	try
		log "Disable scheduled updates..."
		do shell script "softwareupdate --schedule off"
	on error errStr number errorNumber
		recordError(errStr, errorNumber)
		log "Scheduled updates could not be disabled!"
	end try
end rvp_update_system

log "Rise Vision Player Installer ver." & PLAYER_VERSION

rvp_update_system()

rvp_get_update()

-- check for restart first

if (VALUE_RESTART = VALUE_YES) then
	
	rvp_restart()
	
end if

-- check for installer upgrade

if (VALUE_INSTALLER_UPGRADE = VALUE_YES) then
	
	rvp_download_and_run_installer()
	
else
	
	log "Installer is up to date."
	
end if

rvp_install_script()

do shell script "rm -rf " & TEMP_PATH

-- check for Chromium upgrade

if (VALUE_CHROMIUM_VERSION is not equal to "" and VALUE_CHROMIUM_URL is not equal to "") then
	
	rvp_download_and_unpack_chromium()
	set UPGRADE_NEEDED to VALUE_YES
	
else
	if (folderExists(INSTALL_PATH & "/Chromium.app")) then
		log "Chromium is up to date"
	end if
end if

-- install upgrades if necessary

if (UPGRADE_NEEDED = VALUE_YES and (folderExists(CHROME_MAC_PATH))) then
	
	log "Installing updates..."
	rvp_install_chromium()
	log "Updates installed"
	
end if

rvp_add_player_to_autostart()

rvp_install_to_crontab()

rvp_start_player()